package cc.taofoo.NIO;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SelectorTest {


    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        Selector selector = Selector.open();
//        SocketChannel socketChannel = SocketChannel.open();
//        socketChannel.connect(new InetSocketAddress("", 80));

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);


        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                executorService.execute(new Task(socketChannel));
            }
//        selector.close();

        }
    }


}

class Task implements Runnable {

    private SocketChannel socketChannel;

    public Task(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        try {
            synchronized (System.out) {
                ByteBuffer buf = ByteBuffer.allocate(48);
                int read = 0;

                System.out.print(socketChannel.getRemoteAddress()+" ");
                read = socketChannel.read(buf);

                while (read != -1) {
                    buf.flip();
                    while (buf.hasRemaining()) {
                        System.out.print((char) buf.get());
                    }
                    buf.clear();
                    read = socketChannel.read(buf);
                }
                System.out.println();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
